package hackthon.controller;

import hackthon.core.Constant;
import hackthon.core.MyCookie;
import hackthon.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by wuwenhao on 15/1/8.
 */

@Controller
public class Login {


    @Autowired
    public LoginService loginService;

    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request, HttpServletResponse response){
        Cookie cookie = MyCookie.getCookie(Constant.LOGIN_COOKIE_NAME, request);
        int loginStatus = Constant.LOGIN_STATUS_INIT;
        String CurrentUser = null;
        if(cookie!=null && loginService.CookieLogin(cookie.getValue())){
            String token = cookie.getValue();
            String user_pass[] = token.split("_");
            CurrentUser = user_pass[0];
            return "email";
        }else {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            loginStatus = loginService.isLogin(username, password,Constant.USERNAME_PASS_LOGIN);
            if(loginStatus != Constant.LOGIN_STATUS_LOGIN_SUCCESS){
                return "redirect:/login.jsp";
            }else{
                String token = username+"_"+password;
                token = Constant.encodeBASE64(token);
                Cookie loginCookie = MyCookie.addCookie(Constant.LOGIN_COOKIE_NAME,token,null,null,Constant.COOKIE_TRANSIENT_AGE);
                CurrentUser = username;
                response.addCookie(loginCookie);
                return "email";
            }
        }
    }
}
